package cc.io24.knewcafe.boss.controller;

import cc.io24.knewcafe.boss.service.BaseService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;



public class BaseController<T> {


    private BaseService service;

    @GetMapping(value = "",produces="application/json")
    public List<T> getList(@ModelAttribute T t,
                                       @PageableDefault(value = 10, sort = { "createDate" }, direction = Sort.Direction.DESC)Pageable pageable,
                                       HttpServletResponse response){
        Page<T> page =  service.getList(t,pageable);
        response.addHeader("X-Total-Count",page.getTotalElements()+"");
        response.addHeader("Access-Control-Expose-Headers","X-Total-Count");
        return page.getContent();
    }

    @GetMapping(value = "/{id}",produces="application/json")
    public T getOne(@PathVariable("id")String id,
                                   HttpServletResponse response){
        T t =  (T)service.getOne(id);
        return t;
    }


    @PostMapping(value = "",produces="application/json")
    public T create(@RequestBody T t,
                          HttpServletResponse response){
        return (T)service.insert(t);
    }

    @PutMapping(value = "/{id}",produces="application/json")
    public T update(@PathVariable("id")String id,
                          @RequestBody T t,
                          HttpServletResponse response){
        //t.setId(id);
        return (T)service.update(t,id);
    }

    @DeleteMapping(value = "/{id}",produces="application/json")
    public void delete(@PathVariable("id")String id,
                          HttpServletResponse response){
        service.deleteById(id);
    }

    public void setService(BaseService service) {
        this.service = service;
    }

    public BaseService getService() {
        return service;
    }
}
